<?php

namespace App\Http\Controllers\Front;

use App\Interfaces\BrandService;
use App\Interfaces\CategoryService;
use App\Interfaces\GoodsService;
use App\Interfaces\SolrService;
use App\Models\Category;
use App\Models\AdPosition;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Auth,Session;

class CatController extends Controller
{

    public function index($cat_id,Request $request,CategoryService $categoryService,SolrService $solrService,BrandService $brandService,GoodsService $goodsService)
    {
        $cat = Category::find($cat_id);

        if (!$cat) abort(404);
        $depth = $cat->getDepth();

        //用户信息
        $user=Auth::user();

        if ($depth==1){
            $adPosition = AdPosition::where('position_key','cat_focus_'.$cat_id)->get()->toArray();
            return view('front.cat.index',compact(['cat','adPosition','user']));

        }elseif($depth==2||$depth==3){

            if ($depth==2){
                $cat_ids = $categoryService->getChildIds($cat_id)->toArray();
            }else{
                $cat_ids = $categoryService->getBrotherIds($cat_id)->toArray();
            }

            if ($depth==3 && !$request->get('cat_id')){
                $filter['cat_id'] = $cat_id;
                //检索分类
                $filterCategory = $categoryService->getPath($cat_id);
            }elseif ($depth==3 && $request->get('cat_id')){
                $filter['cat_id'] = $request->get('cat_id');
                //检索分类
                $filterCategory = $categoryService->getPath($request->get('cat_id'));
            }elseif ($depth!=3 && $request->get('cat_id')){
                $filter['cat_id'] = $request->get('cat_id');
                //检索分类
                $filterCategory = $categoryService->getPath($request->get('cat_id'));
            }elseif ($depth!=3 && !$request->get('cat_id')){
                $filter['cat_id'] = $request->get('cat_id');
                //检索分类
                $filterCategory = $categoryService->getPath($cat_id);
            }

            $filter['brand_id'] = $request->get('brand_id')?$request->get('brand_id'):0;
            $filter['stock'] = $request->get('stock')?$request->get('stock'):0;
            $filter['sort'] = $request->get('sort');



            $result = $solrService->category($cat_ids,$filter['cat_id'],$filter['brand_id'],$filter['stock'],$request->get('page'),40,$filter['sort']);

            $goodsPaginate = $result['paginate'];

            $catFacet = $result['facetSet']->getFacet('cat_id')->getValues();

            //dd($catFacet);

            //检索品牌
            $filterCat = $categoryService->getCatByIds(array_keys($catFacet));


            return view('front.cat.detail',compact(['cat_id','cat','goodsPaginate','relateKeywords','filter','filterCategory','filterBrand','filterCat','catFacet','brandFacet','keyword','user']));


        }


    }
}
